#include "head.h"

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,4);
    int childNum=atoi(argv[3]);
    processData_t *workerList=(processData_t *)calloc(childNum,sizeof(processData_t));
    make_child(workerList,childNum);//创建子进程

    int sock_fd;
    tcp_init(argv[1],argv[2],&sock_fd);

    //注册监控sock_fd
    int epfd=epoll_create(1);
    epoll_add(epfd,sock_fd);
    //注册监控子进程管道对端
    int i;
    for(i=0;i<childNum;i++)
    {
        epoll_add(epfd,workerList[i].pipeFd);
    }

    int ready_fd_num,new_fd;
    struct epoll_event *evs=(struct epoll_event *)calloc(childNum+1,sizeof(struct epoll_event));
    struct sockaddr_in clientAddr;
    int addrLen,j,finish_flag;//finish_flag用来存储完成标志
    char buf[1000]={0};    
    while (1)
    {
        ready_fd_num=epoll_wait(epfd,evs,childNum+1,-1);
        for(i=0;i<ready_fd_num;i++)
        {
            //sock_fd可读、有人请求链接
            if(sock_fd==evs[i].data.fd)
            {
                addrLen=sizeof(clientAddr);
                new_fd=accept(sock_fd,(struct sockaddr *)&clientAddr,&addrLen);
                printf("task coming ip=%s,port=%d\n",inet_ntoa(clientAddr.sin_addr),ntohs(clientAddr.sin_port));
                //找到非忙碌的子进程、将任务派给他
                for(j=0;j<childNum;j++)
                {
                    if(workerList[j].status==FREE)
                    {
                        sendFd(workerList[j].pipeFd,new_fd);
                        workerList[j].status=BUSY;
                    #ifdef DEBUG
                        printf("%d process receive task\n",workerList[j].pid);
                    #endif
                        break;
                    }
                }
                close(new_fd);
            }else
            {
                //某个子进程管道对端可读
                for(j=0;j<childNum;j++)//寻找是哪个子进程的对端
                {
                    if(workerList[j].pipeFd==evs[i].data.fd)
                    {
                        read(workerList[j].pipeFd,&finish_flag,sizeof(int));
                        workerList[j].status=FREE;
                    #ifdef DEBUG
                        printf("%d process finish task\n",workerList[i].pid);
                    #endif
                        break;
                    }
                }
            }
        }
    }    
}